package main

import (
	"fmt"
	"math/rand"
	"sync"
	"time"
)

func init() {
	rand.Seed(time.Now().Unix())
}

//线程同步  读写锁速度更快 ，与互斥锁性能相差百倍
/*
 a.import("sync")
 b.互斥锁,var mu sync.Mutex
 c.读写锁,var mu sync.RWMutex
*/
func main() {
	//testMutexSync()
	testRWLock()
}

//互斥锁演示
var lock sync.Mutex

func testMutexSync() {
	a := make(map[int]int)
	a[1] = 3
	a[5] = 6
	a[3] = 19
	a[44] = 9
	a[2] = 8
	for i := 0; i < 3; i++ {
		go func(b map[int]int) {
			lock.Lock()
			b[1] = rand.Intn(100)
			lock.Unlock()
		}(a)
	}
	lock.Lock()
	fmt.Println(a)
	lock.Unlock()
	time.Sleep(time.Second)
}

//读写锁演示
var rwLock sync.RWMutex

func testRWLock() {
	a := make(map[int]int)
	a[1] = 3
	a[5] = 6
	a[3] = 19
	a[44] = 9
	a[2] = 8
	for i := 0; i < 3; i++ {
		go func(b map[int]int) {
			rwLock.Lock()
			b[2] = rand.Intn(100)
			rwLock.Unlock()
		}(a)
	}

	for i := 0; i < 100; i++ {
		go func(b map[int]int) {
			rwLock.RLock()
			fmt.Println(b[2])
			rwLock.RUnlock()
		}(a)
	}
	time.Sleep(time.Second * 10)
}
